package com.example.suhui_test;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.ComponentActivity;

// 添加Trace导入
import android.os.Trace;

import com.example.suhui_test.IUserService;
import com.example.suhui_test.ISensorService;
import com.example.suhui_test.ISensorCallback;
import com.example.suhui_test.User;
import com.example.suhui_test.service.UserService;
import com.example.suhui_test.service.SensorService;

import java.util.List;

/**
 * 主Activity
 * 实现AIDL客户端功能，演示用户管理服务和传感器服务的调用
 */
public class MainActivity extends ComponentActivity {
    private static final String TAG = "MainActivity";

    // AIDL服务接口
    private IUserService userService = null;
    private ISensorService sensorService = null;
    private boolean isUserServiceConnected = false;
    private boolean isSensorServiceConnected = false;

    // 传感器数据显示
    private TextView sensorDataView;
    private TextView sensorStatusView;

    // 用户服务连接
    private final ServiceConnection userServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // 添加Trace标记，明确表示Activity接收到的服务连接回调
            Trace.beginSection("Activity_received_onUserServiceConnected");

            Log.d(TAG, "用户服务已连接，组件名称: " + name);
            Log.d(TAG, "服务连接堆栈:", new Throwable("服务连接跟踪"));
            try {
                userService = IUserService.Stub.asInterface(service);
                isUserServiceConnected = true;
                Log.d(TAG, "用户服务绑定成功，接口实例: " + userService);
                showToast("用户服务连接成功");
            } catch (Exception e) {
                Log.e(TAG, "用户服务连接后初始化接口失败", e);
                showToast("用户服务连接后初始化接口失败: " + e.getMessage());
            } finally {
                // 结束Trace标记
                Trace.endSection();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // 添加Trace标记，明确表示Activity接收到的服务断开回调
            Trace.beginSection("Activity_received_onUserServiceDisconnected");

            Log.d(TAG, "用户服务已断开，组件名称: " + name);
            Log.d(TAG, "服务断开堆栈:", new Throwable("服务断开跟踪"));
            userService = null;
            isUserServiceConnected = false;
            Log.d(TAG, "用户服务解绑完成");
            showToast("用户服务连接断开");

            // 结束Trace标记
            Trace.endSection();
        }
    };

    // 传感器服务连接
    private final ServiceConnection sensorServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // 添加Trace标记，明确表示Activity接收到的服务连接回调
            Trace.beginSection("Activity_received_onSensorServiceConnected");

            Log.d(TAG, "传感器服务已连接，组件名称: " + name);
            Log.d(TAG, "传感器服务连接堆栈:", new Throwable("服务连接跟踪"));
            try {
                sensorService = ISensorService.Stub.asInterface(service);
                isSensorServiceConnected = true;
                Log.d(TAG, "传感器服务绑定成功，接口实例: " + sensorService);
                showToast("传感器服务连接成功");
                // 注册回调
                registerSensorCallback();
            } catch (Exception e) {
                Log.e(TAG, "传感器服务连接后初始化接口失败", e);
                showToast("传感器服务连接后初始化接口失败: " + e.getMessage());
            } finally {
                // 结束Trace标记
                Trace.endSection();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // 添加Trace标记，明确表示Activity接收到的服务断开回调
            Trace.beginSection("Activity_received_onSensorServiceDisconnected");

            Log.d(TAG, "传感器服务已断开，组件名称: " + name);
            Log.d(TAG, "传感器服务断开堆栈:", new Throwable("服务断开跟踪"));
            sensorService = null;
            isSensorServiceConnected = false;
            Log.d(TAG, "传感器服务解绑完成");
            showToast("传感器服务连接断开");
            runOnUiThread(() -> {
                updateSensorStatus(false);
            });

            // 结束Trace标记
            Trace.endSection();
        }
    };

    // 传感器回调实现
    private final ISensorCallback sensorCallback = new ISensorCallback.Stub() {
        @Override
        public void onSensorDataReceived(float x, float y, float z) throws RemoteException {
            // 添加Trace标记，明确表示Activity接收到的传感器数据回调
            Trace.beginSection("Activity_received_onSensorDataReceived");
            
            Log.d(TAG, "接收到传感器数据: x=" + x + ", y=" + y + ", z=" + z);
            // 在UI线程更新数据显示
            runOnUiThread(() -> {
                updateSensorData(x, y, z);
            });
            
            // 结束Trace标记
            Trace.endSection();
        }

        @Override
        public void onSensorStatusChanged(boolean isRunning) throws RemoteException {
            // 添加Trace标记，明确表示Activity接收到的传感器状态回调
            Trace.beginSection("Activity_received_onSensorStatusChanged");
            
            Log.d(TAG, "传感器状态变化: " + isRunning);
            // 在UI线程更新状态显示
            runOnUiThread(() -> {
                updateSensorStatus(isRunning);
            });
            
            // 结束Trace标记
            Trace.endSection();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "MainActivity创建，进程ID: " + android.os.Process.myPid());
        Log.d(TAG, "Activity创建堆栈:", new Throwable("Activity创建跟踪"));

        // 创建主布局
        LinearLayout mainLayout = new LinearLayout(this);
        mainLayout.setOrientation(LinearLayout.VERTICAL);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT
        );
        mainLayout.setLayoutParams(layoutParams);
        mainLayout.setPadding(32, 32, 32, 32);

        // 创建连接用户服务按钮
        Button connectUserServiceButton = createButton("连接用户服务", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                connectToUserService();
            }
        });
        mainLayout.addView(connectUserServiceButton);

        // 创建获取所有用户按钮
        Button getAllUsersButton = createButton("获取所有用户", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getAllUsers();
            }
        });
        mainLayout.addView(getAllUsersButton);

        // 创建添加测试用户按钮
        Button addUserButton = createButton("添加测试用户", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addTestUser();
            }
        });
        mainLayout.addView(addUserButton);

        // 创建获取用户数量按钮
        Button getCountButton = createButton("获取用户数量", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getUserCount();
            }
        });
        mainLayout.addView(getCountButton);

        // 创建断开用户服务按钮
        Button disconnectUserServiceButton = createButton("断开用户服务", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                disconnectUserService();
            }
        });
        mainLayout.addView(disconnectUserServiceButton);

        // 添加分割线
        TextView divider = new TextView(this);
        divider.setText("\n------------ 传感器服务 ------------\n");
        mainLayout.addView(divider);

        // 创建连接传感器服务按钮
        Button connectSensorServiceButton = createButton("连接传感器服务", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                connectToSensorService();
            }
        });
        mainLayout.addView(connectSensorServiceButton);

        // 创建启动传感器按钮
        Button startSensorButton = createButton("启动传感器数据", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startSensor();
            }
        });
        mainLayout.addView(startSensorButton);

        // 创建停止传感器按钮
        Button stopSensorButton = createButton("停止传感器数据", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopSensor();
            }
        });
        mainLayout.addView(stopSensorButton);

        // 创建查询传感器状态按钮
        Button checkSensorStatusButton = createButton("查询传感器状态", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkSensorStatus();
            }
        });
        mainLayout.addView(checkSensorStatusButton);

        // 创建断开传感器服务按钮
        Button disconnectSensorServiceButton = createButton("断开传感器服务", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                disconnectSensorService();
            }
        });
        mainLayout.addView(disconnectSensorServiceButton);

        // 创建显示传感器数据的TextView
        sensorDataView = new TextView(this);
        sensorDataView.setText("传感器数据: 未连接");
        sensorDataView.setPadding(0, 16, 0, 16);
        mainLayout.addView(sensorDataView);

        // 创建显示传感器状态的TextView
        sensorStatusView = new TextView(this);
        sensorStatusView.setText("传感器状态: 未运行");
        sensorStatusView.setPadding(0, 16, 0, 16);
        mainLayout.addView(sensorStatusView);

        // 设置布局
        setContentView(mainLayout);
    }

    /**
     * 创建按钮
     */
    private Button createButton(String text, View.OnClickListener onClickListener) {
        Button button = new Button(this);
        button.setText(text);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
        );
        layoutParams.topMargin = 16;
        button.setLayoutParams(layoutParams);
        button.setOnClickListener(onClickListener);
        return button;
    }

    /**
     * 连接用户服务
     */
    private void connectToUserService() {
        Log.d(TAG, "Connect user service button clicked, current connection state: " + isUserServiceConnected);
        Intent intent = new Intent();
        // 修正Intent Action，与AndroidManifest.xml中的配置保持一致
        intent.setAction("com.example.suhui_test.UserService");
        intent.setPackage("com.example.suhui_test");

        Log.d(TAG, "Preparing to bind user service, Intent: " + intent);
        try {
            // 添加Trace标记，明确表示Activity主动发起的绑定服务调用
            Trace.beginSection("Activity_initiated_bindUserService");
            boolean bound = bindService(intent, userServiceConnection, Context.BIND_AUTO_CREATE);
            Log.d(TAG, "Bind user service call result: " + bound);
            if (!bound) {
                Log.w(TAG, "User service binding failed");
                showToast("User service binding failed");
            }
        } catch (Exception e) {
            Log.e(TAG, "User service connection exception", e);
            Log.e(TAG, "Exception stack trace:", e); // Extra stack trace for debugging
            showToast("User service connection exception: " + e.getMessage());
        } finally {
            // 结束Trace标记
            Trace.endSection();
        }
    }

    /**
     * 连接传感器服务
     */
    private void connectToSensorService() {
        Log.d(TAG, "Connect sensor service button clicked, current connection state: " + isSensorServiceConnected);
        Intent intent = new Intent();
        // 修正Intent Action，与AndroidManifest.xml中的配置保持一致
        intent.setAction("com.example.suhui_test.SensorService");
        intent.setPackage("com.example.suhui_test");

        Log.d(TAG, "Preparing to bind sensor service, Intent: " + intent);
        try {
            // 添加Trace标记，明确表示Activity主动发起的绑定服务调用
            Trace.beginSection("Activity_initiated_bindSensorService");
            boolean bound = bindService(intent, sensorServiceConnection, Context.BIND_AUTO_CREATE);
            Log.d(TAG, "Bind sensor service call result: " + bound);
            if (!bound) {
                Log.w(TAG, "Sensor service binding failed");
                showToast("Sensor service binding failed");
            }
        } catch (Exception e) {
            Log.e(TAG, "Sensor service connection exception", e);
            Log.e(TAG, "Exception stack trace:", e); // Extra stack trace for debugging
            showToast("Sensor service connection exception: " + e.getMessage());
        } finally {
            // 结束Trace标记
            Trace.endSection();
        }
    }

    /**
     * 注册传感器回调
     */
    private void registerSensorCallback() {
        if (!isSensorServiceConnected || sensorService == null) {
            Log.w(TAG, "传感器服务未连接，无法启动传感器");
            showToast("传感器服务未连接");
            return;
        }

        try {
            Log.d(TAG, "Registering sensor callback");
            // 添加Trace标记，明确表示Activity主动发起的注册回调调用
            Trace.beginSection("Activity_initiated_registerSensorCallback");
            sensorService.registerCallback(sensorCallback);
            Log.d(TAG, "传感器回调注册成功");
        } catch (RemoteException e) {
            Log.e(TAG, "Register sensor callback remote exception", e);
            Log.e(TAG, "远程异常堆栈跟踪:", e); // Extra stack trace for debugging
            showToast("Register sensor callback exception: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Register sensor callback unknown exception", e);
            Log.e(TAG, "未知异常堆栈跟踪:", e); // Extra stack trace for debugging
            showToast("Register sensor callback exception: " + e.getMessage());
        } finally {
            // 结束Trace标记
            Trace.endSection();
        }
    }

    /**
     * 启动传感器数据采集
     */
    private void startSensor() {
        if (!isSensorServiceConnected || sensorService == null) {
            Log.w(TAG, "传感器服务未连接，无法启动传感器");
            showToast("传感器服务未连接");
            return;
        }

        try {
            Log.d(TAG, "Starting sensor data collection");
            // 添加Trace标记，明确表示Activity主动发起的启动传感器调用
            Trace.beginSection("Activity_initiated_startSensor");
            sensorService.startSensor();
            Log.d(TAG, "传感器数据采集已启动");
            showToast("传感器数据采集已启动");
        } catch (RemoteException e) {
            Log.e(TAG, "Start sensor remote exception", e);
            Log.e(TAG, "远程异常堆栈跟踪:", e); // Extra stack trace for debugging
            showToast("Start sensor exception: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Start sensor unknown exception", e);
            Log.e(TAG, "未知异常堆栈跟踪:", e); // Extra stack trace for debugging
            showToast("Start sensor exception: " + e.getMessage());
        } finally {
            // 结束Trace标记
            Trace.endSection();
        }
    }

    /**
     * 停止传感器数据采集
     */
    private void stopSensor() {
        if (!isSensorServiceConnected || sensorService == null) {
            Log.w(TAG, "传感器服务未连接，无法停止传感器");
            showToast("传感器服务未连接");
            return;
        }

        try {
            Log.d(TAG, "Stopping sensor data collection");
            // 添加Trace标记，明确表示Activity主动发起的停止传感器调用
            Trace.beginSection("Activity_initiated_stopSensor");
            sensorService.stopSensor();
            Log.d(TAG, "传感器数据采集已停止");
            showToast("传感器数据采集已停止");
        } catch (RemoteException e) {
            Log.e(TAG, "Stop sensor remote exception", e);
            Log.e(TAG, "远程异常堆栈跟踪:", e); // Extra stack trace for debugging
            showToast("Stop sensor exception: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Stop sensor unknown exception", e);
            Log.e(TAG, "未知异常堆栈跟踪:", e); // Extra stack trace for debugging
            showToast("Stop sensor exception: " + e.getMessage());
        } finally {
            // 结束Trace标记
            Trace.endSection();
        }
    }

    /**
     * 查询传感器状态
     */
    private void checkSensorStatus() {
        if (!isSensorServiceConnected || sensorService == null) {
            Log.w(TAG, "传感器服务未连接，无法查询传感器状态");
            showToast("传感器服务未连接");
            return;
        }

        try {
            Log.d(TAG, "Checking sensor status");
            // 添加Trace标记，明确表示Activity主动发起的查询传感器状态调用
            Trace.beginSection("Activity_initiated_checkSensorStatus");
            boolean isRunning = sensorService.isSensorRunning();
            Log.d(TAG, "传感器运行状态: " + isRunning);
            showToast("传感器状态: " + (isRunning ? "运行中" : "已停止"));
            // 更新UI显示
            updateSensorStatus(isRunning);
        } catch (RemoteException e) {
            Log.e(TAG, "Check sensor status remote exception", e);
            Log.e(TAG, "远程异常堆栈跟踪:", e); // Extra stack trace for debugging
            showToast("Check sensor status exception: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Check sensor status unknown exception", e);
            Log.e(TAG, "未知异常堆栈跟踪:", e); // Extra stack trace for debugging
            showToast("Check sensor status exception: " + e.getMessage());
        } finally {
            // 结束Trace标记
            Trace.endSection();
        }
    }

    /**
     * 获取所有用户
     */
    private void getAllUsers() {
        Log.d(TAG, "Get all users button clicked");
        if (!isUserServiceConnected || userService == null) {
            Log.w(TAG, "User service not connected, cannot get user list");
            showToast("User service not connected");
            return;
        }

        try {
            Log.d(TAG, "Calling getAllUsers() method");
            // 添加Trace标记，明确表示Activity主动发起的获取所有用户调用
            Trace.beginSection("Activity_initiated_getAllUsers");
            long startTime = System.currentTimeMillis();
            List<User> users = userService.getAllUsers();
            long endTime = System.currentTimeMillis();
            Log.d(TAG, "getAllUsers() call completed, time taken: " + (endTime - startTime) + "ms");

            String message;
            if (users != null && !users.isEmpty()) {
                Log.d(TAG, "User list obtained, count: " + users.size());
                StringBuilder userInfoBuilder = new StringBuilder();
                for (User user : users) {
                    userInfoBuilder.append("ID: ").append(user.getId())
                            .append(", Name: " ).append(user.getName())
                            .append(", Email: " ).append(user.getEmail())
                            .append("\n");
                }
                message = "User list:\n" + userInfoBuilder.toString();
            } else {
                Log.d(TAG, "No user data obtained");
                message = "No user data available";
            }
            showToast(message);
        } catch (RemoteException e) {
            Log.e(TAG, "Get user list remote exception", e);
            Log.e(TAG, "远程异常堆栈跟踪:", e); // Extra stack trace for debugging
            showToast("Get user list exception: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Get user list unknown exception", e);
            Log.e(TAG, "未知异常堆栈跟踪:", e); // Extra stack trace for debugging
            showToast("Get user list exception: " + e.getMessage());
        } finally {
            // 结束Trace标记
            Trace.endSection();
        }
    }

    /**
     * 添加测试用户
     */
    private void addTestUser() {
        Log.d(TAG, "Add test user button clicked");
        if (!isUserServiceConnected || userService == null) {
            Log.w(TAG, "User service not connected, cannot add user");
            showToast("User service not connected");
            return;
        }

        try {
            Log.d(TAG, "Preparing to create test user");
            User testUser = new User();
            testUser.setId((int) (System.currentTimeMillis() / 1000));
            testUser.setName("Test User");
            testUser.setEmail("test@example.com");
            Log.d(TAG, "Created test user: " + testUser);

            // 添加Trace标记，明确表示Activity主动发起的添加用户调用
            Trace.beginSection("Activity_initiated_addUser");
            long startTime = System.currentTimeMillis();
            userService.addUser(testUser);
            long endTime = System.currentTimeMillis();
            Log.d(TAG, "addUser() call completed, time taken: " + (endTime - startTime) + "ms");

            showToast("Test user added successfully");
        } catch (RemoteException e) {
            Log.e(TAG, "Add user remote exception", e);
            Log.e(TAG, "远程异常堆栈跟踪:", e); // Extra stack trace for debugging
            showToast("Add user exception: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Add user unknown exception", e);
            Log.e(TAG, "未知异常堆栈跟踪:", e); // Extra stack trace for debugging
            showToast("Add user exception: " + e.getMessage());
        } finally {
            // 结束Trace标记
            Trace.endSection();
        }
    }

    /**
     * 获取用户数量
     */
    private void getUserCount() {
        Log.d(TAG, "Get user count button clicked");
        if (!isUserServiceConnected || userService == null) {
            Log.w(TAG, "User service not connected, cannot get user count");
            showToast("User service not connected");
            return;
        }

        try {
            Log.d(TAG, "Calling getUserCount() method");
            // 添加Trace标记，明确表示Activity主动发起的获取用户数量调用
            Trace.beginSection("Activity_initiated_getUserCount");
            long startTime = System.currentTimeMillis();
            int count = userService.getUserCount();
            long endTime = System.currentTimeMillis();
            Log.d(TAG, "getUserCount() call completed, time taken: " + (endTime - startTime) + "ms, count: " + count);

            showToast("Current user count: " + count);
        } catch (RemoteException e) {
            Log.e(TAG, "Get user count remote exception", e);
            Log.e(TAG, "远程异常堆栈跟踪:", e); // Extra stack trace for debugging
            showToast("Get user count exception: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Get user count unknown exception", e);
            Log.e(TAG, "未知异常堆栈跟踪:", e); // Extra stack trace for debugging
            showToast("Get user count exception: " + e.getMessage());
        } finally {
            // 结束Trace标记
            Trace.endSection();
        }
    }

    /**
     * 断开用户服务
     */
    private void disconnectUserService() {
        Log.d(TAG, "Disconnect user service button clicked, current connection state: " + isUserServiceConnected);
        if (isUserServiceConnected) {
            Log.d(TAG, "Executing unbind user service operation");
            try {
                // 添加Trace标记，明确表示Activity主动发起的解绑服务调用
                Trace.beginSection("Activity_initiated_unbindUserService");
                unbindService(userServiceConnection);
                isUserServiceConnected = false;
                Log.d(TAG, "User service unbound successfully");
                showToast("User service disconnected");
            } catch (Exception e) {
                Log.e(TAG, "User service unbind exception", e);
                Log.e(TAG, "解绑异常堆栈跟踪:", e); // Extra stack trace for debugging
                showToast("User service unbind exception: " + e.getMessage());
            } finally {
                // 结束Trace标记
                Trace.endSection();
            }
        } else {
            Log.w(TAG, "User service not connected, no need to unbind");
            showToast("User service not connected");
        }
    }

    /**
     * 断开传感器服务
     */
    private void disconnectSensorService() {
        Log.d(TAG, "Disconnect sensor service button clicked, current connection state: " + isSensorServiceConnected);
        if (isSensorServiceConnected && sensorService != null) {
            Log.d(TAG, "Executing unregister callback and unbind sensor service operation");
            try {
                // 先注销回调
                Trace.beginSection("Activity_initiated_unregisterSensorCallback");
                sensorService.unregisterCallback(sensorCallback);
                Log.d(TAG, "传感器回调注销成功");
                Trace.endSection();
            } catch (Exception e) {
                Log.e(TAG, "Unregister sensor callback exception", e);
            }
            
            try {
                // 再解绑服务
                Trace.beginSection("Activity_initiated_unbindSensorService");
                unbindService(sensorServiceConnection);
                isSensorServiceConnected = false;
                Log.d(TAG, "传感器服务解绑成功");
                showToast("传感器服务连接断开");
            } catch (Exception e) {
                Log.e(TAG, "传感器服务解绑异常", e);
                Log.e(TAG, "解绑异常堆栈跟踪:", e); // Extra stack trace for debugging
                showToast("传感器服务解绑异常: " + e.getMessage());
            } finally {
                // 结束Trace标记
                Trace.endSection();
            }
        } else {
            Log.w(TAG, "传感器服务未连接，无需解绑");
            showToast("传感器服务未连接");
        }
    }

    /**
     * 显示Toast消息
     */
    private void showToast(String message) {
        Log.d(TAG, "显示Toast消息: " + message);
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }

    /**
     * 更新传感器数据显示
     */
    private void updateSensorData(float x, float y, float z) {
        String sensorDataText = String.format("传感器数据: x=%.4f, y=%.4f, z=%.4f", x, y, z);
        sensorDataView.setText(sensorDataText);
    }

    /**
     * 更新传感器状态显示
     */
    private void updateSensorStatus(boolean isRunning) {
        String statusText = "传感器状态: " + (isRunning ? "运行中" : "已停止");
        sensorStatusView.setText(statusText);
    }

    @Override
    protected void onDestroy() {
        Log.d(TAG, "MainActivity销毁开始");
        Log.d(TAG, "Activity销毁堆栈:", new Throwable("Activity销毁跟踪"));
        // 添加Trace标记，明确表示Activity生命周期事件
        Trace.beginSection("Activity_生命周期_onDestroy");
        
        // 解绑用户服务
        if (isUserServiceConnected) {
            Log.d(TAG, "Activity销毁时解绑用户服务");
            try {
                // 添加Trace标记，明确表示Activity在销毁时主动发起的解绑服务调用
                Trace.beginSection("Activity_生命周期_onDestroy_unbindUserService");
                unbindService(userServiceConnection);
                Log.d(TAG, "Activity销毁时用户服务解绑成功");
                // 结束Trace标记
                Trace.endSection();
            } catch (Exception e) {
                Log.e(TAG, "Activity销毁时用户服务解绑异常", e);
            }
        }
        
        // 解绑传感器服务
        if (isSensorServiceConnected && sensorService != null) {
            Log.d(TAG, "Activity销毁时解绑传感器服务");
            try {
                // 先注销回调
                Trace.beginSection("Activity_生命周期_onDestroy_unregisterSensorCallback");
                sensorService.unregisterCallback(sensorCallback);
                Log.d(TAG, "Activity销毁时传感器回调注销成功");
                Trace.endSection();
            } catch (Exception e) {
                Log.e(TAG, "Activity销毁时传感器回调注销异常", e);
            }
            
            try {
                // 再解绑服务
                Trace.beginSection("Activity_生命周期_onDestroy_unbindSensorService");
                unbindService(sensorServiceConnection);
                Log.d(TAG, "Activity销毁时传感器服务解绑成功");
                // 结束Trace标记
                Trace.endSection();
            } catch (Exception e) {
                Log.e(TAG, "Activity销毁时传感器服务解绑异常", e);
            }
        }
        
        super.onDestroy();
        Log.d(TAG, "MainActivity销毁完成");
        // 结束Trace标记
        Trace.endSection();
    }
}